<template>
  <CommonDialog v-model="visible" title="角色授权" :loading="loading" :width="500" @submit="submit"
    @cancel="cancel">
    <el-tree ref="treeRef" :data="treeData" show-checkbox node-key="id" :props="{
      children: 'children',
      label: 'name'
    }" :expand-on-click-node="false" highlight-current/>
  </CommonDialog>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'

import { roleAuth, roleSave } from '@/api/modules/role'

import { listToTree } from '@/util'

import { ElTree } from 'element-plus'
import { Message } from 'view-ui-plus'

const visible = ref(true)
const treeRef = ref(null)
const treeData = ref([
  {  name: '全部菜单', id: 0, children: [] }
])
const loading = ref(false)
const props = defineProps({
  roleId: String
})

const emit = defineEmits(['cancel'])

const getTreeData = () => {
  roleAuth({
    data: {
      id: props.roleId
    }
  }).then(({ data }) => {
    treeData.value[0].children = listToTree(data.resourceList, {
      id: 'id',
      children: 'children',
      pid: 'parentid'
    })

    const selectedIds = data.roleAuthList.map(item=>item.dicid)
    nextTick(()=>{
      treeRef.value.setCheckedKeys(selectedIds)
    })
    
  })
}

const submit = async () => {
  const treeIds = treeRef.value.getCheckedKeys()
  const treePids = treeRef.value.getHalfCheckedKeys()
  const ids =  [...treePids, ...treeIds].filter(item=>item)

  loading.value = true

  try {
    await roleSave({
      data: {
        ids,
        id: props.roleId
      }
    })

    Message.success('操作成功')
    cancel()
  } catch (error) {
    console.error(error)
  }

  loading.value = false
}

const cancel = () => {
  emit('cancel')
}

onMounted(() => {
  getTreeData()
})
</script>

<style scoped lang="scss">
.el-tree {
  overflow-y: auto;
  height: 600px;
}
</style>